import 'dart:async';

import 'package:chewie/chewie.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_sound/flutter_sound.dart';
import 'package:screen/screen.dart';
import 'package:studymanage/core/event_bus.dart';
import 'package:studymanage/core/global.dart';
import 'package:studymanage/core/sound/ui/demo_active_codec.dart';
import 'package:studymanage/core/sound/ui/remote_player.dart';
import 'package:studymanage/core/sound/util/format.dart';
import 'package:studymanage/course/share.dart';
import 'package:studymanage/remark/toRemark.dart';
import 'package:studymanage/util/Event.dart';
import 'package:studymanage/util/fun.dart';
import 'package:studymanage/util/request.dart';
import 'package:video_player/video_player.dart';
import 'package:audioplayers/audioplayers.dart';
class CourseDetail extends StatefulWidget {
  final Map<String,dynamic> detail;
  final String courseId;
  final update ;

  CourseDetail(this.detail,this.courseId,this.update);

  @override
  State<StatefulWidget> createState() {
    return CourseDetailState();
  }
}

class CourseDetailState extends State<CourseDetail>{
  ScrollController _scrollController = ScrollController();
  bool isLoading = false;
  int _page=1;
  int _currentTab = 0;
  Map _courseDetail ;
  String _courseId;
  int currVideo=-1;
  List _remarkList = [];

  AudioPlayer audioPlayer = AudioPlayer();
  int currindex = 0;

  Timer _timer; // 播放计时器

  VideoPlayerController _videoPlayerController;
  ChewieController _chewieController;

  @override
  void initState() {
    eventBus.on<UserLoggedInEvent>().listen((event) {
      print("1111"+event.code);
      if(event.code == "s"){
        _chewieController.pause();
      }
    });
    _scrollController.addListener(() {
      if(_scrollController.position.pixels >
          _scrollController.position.maxScrollExtent-20){
        _getMark(_courseDetail['taskId']);
      }
    });
    super.initState();
    setState(() {
      _courseDetail = widget.detail;
      _courseId =widget.courseId;
    });
    // 初始化视频
    initVideo(_courseDetail['taTaskContentList']);
    audioPlayer.onDurationChanged.listen((Duration d) {
      setState(() {
        _courseDetail['taTaskContentList'][currindex]['initSchedule']  = d;
      });
    });

    audioPlayer.onAudioPositionChanged.listen((Duration  p) {
        setState(() {
          if(p.inMilliseconds >= _courseDetail['taTaskContentList'][currindex]['currentSchedule'].inMilliseconds){
            _courseDetail['taTaskContentList'][currindex]['currentSchedule'] = p;
          }
        });
    });
    audioPlayer.onPlayerStateChanged.listen((AudioPlayerState s) {
      setState(() {
        _courseDetail['taTaskContentList'][currindex]['isPlayAudio'] = s;
      });
      print('Current player state: $s');
    });
    audioPlayer.onPlayerCompletion.listen((event) {
      setState(() {
        _courseDetail['taTaskContentList'][currindex]['isPlayAudio'] = AudioPlayerState.COMPLETED;
      });
    });
    audioPlayer.onPlayerError.listen((msg) {
      print('audioPlayer error : $msg');
    });

  }
  initVideo(tasks){
    tasks.forEach((element) {
      if (element['taskContentTypeEnum'] == 4) {
        setState(() {
          element['videoPaly']=false;
        });
      }
      if (element['taskContentTypeEnum'] == 3) {
        element['isPlayAudio'] = AudioPlayerState.STOPPED;
        element['initSchedule'] = Duration();
        element['currentSchedule'] = Duration();
      }
    });
  }

  @override
  void dispose() {
    audioPlayer.stop();
    audioPlayer.release();
    if (_timer != null) {
      _timer.cancel();
      _timer = null;
    }
    if(_videoPlayerController!=null){
      _videoPlayerController.dispose();
    }
    if(_chewieController!=null){
      _chewieController.dispose();
    }
    Screen.isKeptOn.then((value) => {
      if(value) {
        Screen.keepOn(false)
      }
    });
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: SafeArea(
        child: Container(
          constraints: BoxConstraints(
            minHeight: MediaQuery.of(context).size.height
          ),
          child: Stack(
            children: <Widget>[
              Container(
                padding: EdgeInsets.only(
                  top: ScreenUtil().setHeight(46),
                  bottom: ScreenUtil().setHeight(50),
                ),
                child: Stack(
                  children: <Widget>[
                    Offstage(
                      offstage: _currentTab != 0,
                      child: SingleChildScrollView(
                        child: Container(
                          width: MediaQuery.of(context).size.width,
                          padding: EdgeInsets.only(
                            top: ScreenUtil().setHeight(23),
                            left: ScreenUtil().setWidth(15),
                            right: ScreenUtil().setWidth(15),
                          ),
                          margin: EdgeInsets.only(bottom: 40),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: <Widget>[
                              Text(_courseDetail['taskTitle'],
                                style: TextStyle(
                                  fontFamily: 'PingFangSC-Medium',
                                  fontSize: ScreenUtil().setSp(18),
                                  fontWeight: FontWeight.w600,
                                  color: Color.fromRGBO(51, 51, 51, 1),
                                  height: 1,
                                ),
                              ),
                              Container(
                                margin: EdgeInsets.only(
                                  top: ScreenUtil().setHeight(15),
                                ),
                                child: Text(_courseDetail['courseName'],
                                  style: TextStyle(
                                    fontFamily: 'PingFangSC-Regular',
                                    fontSize: ScreenUtil().setSp(11),
                                    color: Color.fromRGBO(210, 180, 142, 1),
                                    height: 1,
                                  ),
                                ),
                              ),
                              Container(
                                margin: EdgeInsets.only(
                                  top: ScreenUtil().setHeight(15),
                                ),
                                child: ListView.builder(
                                  shrinkWrap: true,
                                  physics: NeverScrollableScrollPhysics(),
                                  itemCount: _courseDetail['taTaskContentList'].length,
                                  itemBuilder: (context, index) {
                                    List _cache = _courseDetail['taTaskContentList'];

                                    if (_cache[index]['taskContentTypeEnum'] == 2) {  // 文本
                                      return Container(
                                        margin: EdgeInsets.only(
                                          bottom: ScreenUtil().setHeight(20),
                                        ),
                                        child: Text(_cache[index]['taskContentContent'],
                                          style: TextStyle(
                                            fontFamily: 'PingFangSC-Light',
                                            fontSize: ScreenUtil().setSp(14),
                                            fontWeight: FontWeight.w300,
                                            color: Color.fromRGBO(51, 51, 51, 1),
                                          ),
                                        ),
                                      );
                                    } else if (_cache[index]['taskContentTypeEnum'] == 1) { // 图片
                                      return Container(
                                        margin: EdgeInsets.only(
                                          bottom: ScreenUtil().setHeight(20),
                                        ),
                                        child: Image.network(_cache[index]['taskContentContent'],
                                          fit: BoxFit.fitWidth,
                                        ),
                                      );
                                    } else if (_cache[index]['taskContentTypeEnum'] == 3) { // 音频
                                      return Container(
                                        margin: EdgeInsets.only(
                                          bottom: ScreenUtil().setHeight(10),
                                        ),
                                        decoration: BoxDecoration(
                                          border: Border.all(
                                            color: Color.fromRGBO(214, 178, 128, 1),
                                            width: ScreenUtil().setHeight(1),
                                          ),
                                          borderRadius: BorderRadius.all(
                                            Radius.circular(5),
                                          ),
                                        ),
                                        child: Row(
                                          children: [
                                            IconButton(
                                              padding:EdgeInsets.all(0),
                                              icon: _courseDetail['taTaskContentList'][index]['isPlayAudio'] == AudioPlayerState.STOPPED||_courseDetail['taTaskContentList'][index]['isPlayAudio'] == AudioPlayerState.PAUSED ? Icon(Icons.play_arrow,color: Color.fromRGBO(214, 178, 128, 1),) : Icon(Icons.stop,color: Color.fromRGBO(214, 178, 128, 1),) ,
                                              onPressed: (){
                                                if( _chewieController !=null && _chewieController.videoPlayerController.value.isPlaying){
                                                  _chewieController.pause();
                                                }
                                                bool isNext = index != currindex;
                                                setState(() {
                                                  if(isNext){
                                                    _courseDetail['taTaskContentList'][currindex]['isPlayAudio'] = AudioPlayerState.PAUSED;
                                                    _courseDetail['taTaskContentList'][currindex]['currentSchedule'] = new Duration();
                                                  }
                                                  currindex = index;
                                                });

                                                if(_courseDetail['taTaskContentList'][index]['isPlayAudio'] == AudioPlayerState.STOPPED){
                                                  audioPlayer.play(_courseDetail['taTaskContentList'][index]['taskContentContent']);
                                                }else if(_courseDetail['taTaskContentList'][index]['isPlayAudio'] == AudioPlayerState.PAUSED){
                                                  if(isNext){
                                                    audioPlayer.play(_courseDetail['taTaskContentList'][index]['taskContentContent']);
                                                  }else{
                                                    audioPlayer.resume();
                                                  }
                                                }else if(_courseDetail['taTaskContentList'][index]['isPlayAudio'] == AudioPlayerState.PLAYING){
                                                  audioPlayer.pause();
                                                }else if(_courseDetail['taTaskContentList'][index]['isPlayAudio'] == AudioPlayerState.COMPLETED){
                                                  audioPlayer.play(_courseDetail['taTaskContentList'][index]['taskContentContent']);
                                                }
                                              },
                                            ),
                                            Text(Format.duration(_courseDetail['taTaskContentList'][index]['currentSchedule'],showSuffix: false).toString()+"/"+Format.duration(_courseDetail['taTaskContentList'][index]['initSchedule'],showSuffix: false).toString(),style: TextStyle(fontSize: 12,color: Color.fromRGBO(214, 178, 128, 1)),),
                                            Expanded(
                                                child: SliderTheme(
                                                  data: SliderThemeData(
                                                    thumbShape: RoundSliderThumbShape(enabledThumbRadius: 6.0),
                                                    //thumbColor: Colors.amber,
                                                    thumbColor: Color.fromRGBO(214, 178, 128, 1),
                                                    inactiveTrackColor: Color.fromRGBO(214, 178, 128, 0.5),
                                                    activeTrackColor: Color.fromRGBO(214, 178, 128, 1),
                                                  ),
                                                  child: Slider(
                                                      max: _courseDetail['taTaskContentList'][index]['initSchedule'].inMilliseconds.toDouble(),
                                                      value: _courseDetail['taTaskContentList'][index]['currentSchedule'].inMilliseconds.toDouble(),
                                                      onChanged: (value) {
                                                        audioPlayer.seek(Duration(milliseconds: value.toInt()));
                                                        print(value);
                                                      }
                                                  ),
                                                )
                                            ),
                                          ],
                                        ),

                                      );
                                    } else if (_cache[index]['taskContentTypeEnum'] == 4) { // 视频
                                      return GestureDetector(
                                        child: Container(
                                          margin: EdgeInsets.only(
                                            bottom: ScreenUtil().setHeight(20),
                                          ),
                                          color: Colors.black,
                                          child: Theme(
                                            data: ThemeData(
                                              dialogBackgroundColor: Colors.grey.withOpacity(0.4),
                                            ),
                                            child: Container(
                                              child: _cache[index]['videoPaly'] ?  Chewie(
                                                controller: _chewieController,
                                              ):Container(
                                                height: MediaQuery.of(context).size.width/2,
                                                child: Icon(Icons.play_circle_outline,color: Colors.grey,size: 40,),
                                              ),
                                            ),
                                          ),
                                        ),
                                        onTap: ()=>_videoPlay(index,_cache),
                                      );
                                    } else { // 其他
                                      return Text(_cache[index]['taskContentContent']);
                                    }
                                  },
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                    ),
                    //功课点评
                    Offstage(
                      offstage: _currentTab != 1,
                      child: Container(
                        width: MediaQuery.of(context).size.width,
                        padding: EdgeInsets.only(
                          left: ScreenUtil().setWidth(12.5),
                          right: ScreenUtil().setWidth(12.5),
                        ),
                        child: ListView.builder(
                          physics: BouncingScrollPhysics(),
                          controller: _scrollController,
                          itemCount: _remarkList.length,
                          itemBuilder: (context, index) {
                            return Container(
                              margin: EdgeInsets.only(top:10),
                              color: Colors.white,
                              child: Column(
                                children: <Widget>[
                                  Container(
                                    padding: EdgeInsets.all(13),
                                    decoration: BoxDecoration(
                                        color: Color(0xffF8F8F8),
                                        borderRadius: BorderRadius.circular(4)
                                    ),
                                    child: Column(
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      children: <Widget>[
                                        Row(
                                          crossAxisAlignment: CrossAxisAlignment.start,
                                          children: <Widget>[
                                            Container(
                                              height: 41,
                                              width: 41,
                                              child: CircleAvatar(
                                                backgroundImage: NetworkImage(_remarkList[index]['studentAvatar']),
                                                radius: ScreenUtil().setWidth(20.5),
                                              ),
                                            ),
                                            Expanded(
                                              child: Container(
                                                margin: EdgeInsets.only(left: 10),
                                                child: Column(
                                                  crossAxisAlignment: CrossAxisAlignment.start,
                                                  children: <Widget>[
                                                    Row(
                                                      children: <Widget>[
                                                        Text(
                                                          _remarkList[index]['studentNickname'],
                                                          style: TextStyle(
                                                            fontFamily: 'PingFangSC-Medium',
                                                            fontSize: ScreenUtil().setSp(14),
                                                            fontWeight: FontWeight.w600,
                                                            color: Color.fromRGBO(51, 51, 51, 1),
                                                            height: 1,
                                                          ),
                                                        ),
                                                        Offstage(
                                                          offstage: !_remarkList[index]['studentOwn'],
                                                          child: Container(
                                                            padding: EdgeInsets.all(3),
                                                            margin: EdgeInsets.only(
                                                              left: ScreenUtil().setWidth(9.5),
                                                            ),
                                                            decoration: BoxDecoration(
                                                              border: Border.all(
                                                                color: Color.fromRGBO(133, 133, 133, 1),
                                                                width: ScreenUtil().setHeight(0.5),
                                                              ),
                                                              borderRadius: BorderRadius.all(
                                                                Radius.circular(ScreenUtil().setHeight(2)),
                                                              ),
                                                            ),
                                                            child: Text(
                                                              '自己',
                                                              style: TextStyle(
                                                                fontFamily: 'PingFangSC-Light',
                                                                fontSize: ScreenUtil().setSp(10),
                                                                fontWeight: FontWeight.w300,
                                                                color: Color.fromRGBO(133, 133, 133, 1),
                                                              ),
                                                            ),
                                                          ),
                                                        ),
                                                        Offstage(
                                                          offstage: !_remarkList[index]['boolComplete'],
                                                          child: Container(
                                                            padding: EdgeInsets.all(3),
                                                            margin: EdgeInsets.only(
                                                              left: 3,
                                                            ),
                                                            decoration: BoxDecoration(
                                                              border: Border.all(
                                                                color: Color.fromRGBO(133, 133, 133, 1),
                                                                width: ScreenUtil().setHeight(0.5),
                                                              ),
                                                              borderRadius: BorderRadius.all(
                                                                Radius.circular(ScreenUtil().setHeight(2)),
                                                              ),
                                                            ),
                                                            child: Text(
                                                              "已经结业",
                                                              style: TextStyle(
                                                                fontFamily: 'PingFangSC-Light',
                                                                fontSize: ScreenUtil().setSp(10),
                                                                fontWeight: FontWeight.w300,
                                                                color: Color.fromRGBO(133, 133, 133, 1),
                                                              ),
                                                            ),
                                                          ),
                                                        ),
                                                      ],
                                                    ),
                                                    Container(
                                                      margin: EdgeInsets.only(top: 5),
                                                      child: Row(
                                                        children: <Widget>[
                                                          Container(
                                                            child: Text(
                                                              _remarkList[index]['shareDateCN'],
                                                              style: TextStyle(
                                                                fontFamily: 'PingFangSC-Light',
                                                                fontSize: ScreenUtil().setSp(11),
                                                                fontWeight: FontWeight.w300,
                                                                color: Color.fromRGBO(133, 133, 133, 1),
                                                                height: 1,
                                                              ),
                                                            ),
                                                          ),
                                                          Offstage(
                                                            offstage: _remarkList[index]['shareRecordContentVoice']=="",
                                                            child:GestureDetector(
                                                              child:Container(
                                                                margin: EdgeInsets.only(left: 8),
                                                                child: Image.asset("assets/images/mine/ydp_bfanky.png")
                                                            ),
                                                            onTap: (){
                                                                audioPlayer.stop();
                                                                audioPlayer.play(_remarkList[index]['shareRecordContentVoice']);
                                                            },
                                                          ),
                                                          )
                                                        ],
                                                      ),
                                                    )
                                                  ],
                                                ),
                                              ),
                                            ),
                                            Offstage(
                                              offstage: _remarkList[index]['boolCommentEnum'] == 1|| Global.profile.userTypeEnum ==1,
                                              child: Container(
                                                width: 42,
                                                height: 23,
                                                decoration: BoxDecoration(
                                                    color: Color.fromRGBO(214, 178, 128, 1),
                                                    borderRadius: BorderRadius.circular(2)
                                                ),
                                                child: FlatButton(
                                                  padding: EdgeInsets.all(0),
                                                  child: Text(
                                                    '点评',
                                                    style: TextStyle(
                                                      fontFamily: 'PingFangSC-Regular',
                                                      fontSize: ScreenUtil().setSp(12),
                                                      color: Colors.white,
                                                    ),
                                                  ),
                                                  onPressed: () {
                                                    Navigator.push(context, MaterialPageRoute(builder: (context) => ToRemark(_remarkList[index],()=>_update())));
                                                  },
                                                ),
                                              ),
                                            ),
                                          ],
                                        ),
                                        Container(
                                          margin: EdgeInsets.only(left: 51,top: 10),
                                          child: Text(_remarkList[index]['shareRecordContent']),
                                        )

                                      ],
                                    ),
                                  ),
                                  Offstage(
                                    offstage: _remarkList[index]['boolCommentEnum'] != 1,
                                    child: Container(
                                      margin: EdgeInsets.only(top: 23),
                                      child: Column(
                                        crossAxisAlignment: CrossAxisAlignment.end,
                                        children: <Widget>[
                                          Row(
                                            mainAxisAlignment: MainAxisAlignment.end,
                                            crossAxisAlignment: CrossAxisAlignment.center,
                                            children: <Widget>[
                                              Column(
                                                crossAxisAlignment: CrossAxisAlignment.end,
                                                children: <Widget>[
                                                  Row(
                                                    crossAxisAlignment: CrossAxisAlignment.center,
                                                    children: <Widget>[
                                                      Container(
                                                        padding: EdgeInsets.only(
                                                          left: ScreenUtil().setWidth(4.5),
                                                          right: ScreenUtil().setWidth(4.5),
                                                          top: ScreenUtil().setHeight(3.5),
                                                          bottom: ScreenUtil().setHeight(3.5),
                                                        ),
                                                        margin: EdgeInsets.only(
                                                          right: ScreenUtil().setWidth(9.5),
                                                        ),
                                                        decoration: BoxDecoration(
                                                          border: Border.all(
                                                            color: Color.fromRGBO(133, 133, 133, 1),
                                                            width: ScreenUtil().setHeight(0.5),
                                                          ),
                                                          borderRadius: BorderRadius.all(
                                                            Radius.circular(ScreenUtil().setHeight(2)),
                                                          ),
                                                        ),
                                                        child: Text(
                                                          '情感导师点评',
                                                          style: TextStyle(
                                                            fontFamily: 'PingFangSC-Light',
                                                            fontSize: ScreenUtil().setSp(10),
                                                            fontWeight: FontWeight.w300,
                                                            color: Color.fromRGBO(133, 133, 133, 1),
                                                          ),
                                                        ),
                                                      ),
                                                      Text(
                                                        _remarkList[index]['teacherNickname']==null ? "-" : _remarkList[index]['teacherNickname'],
                                                        style: TextStyle(
                                                          fontFamily: 'PingFangSC-Medium',
                                                          fontSize: ScreenUtil().setSp(14),
                                                          fontWeight: FontWeight.w600,
                                                          color: Color.fromRGBO(51, 51, 51, 1),
                                                          height: 1,
                                                        ),
                                                      ),
                                                    ],
                                                  ),
                                                  Container(
                                                    margin: EdgeInsets.only(top: 5),
                                                    child: Row(
                                                      children: <Widget>[
                                                        Container(
                                                          margin: EdgeInsets.only(right: 8),
                                                          child: Text(
                                                            _remarkList[index]['commentDateCN'] != null ? _remarkList[index]['commentDateCN'] : '',
                                                            style: TextStyle(
                                                              fontFamily: 'PingFangSC-Light',
                                                              fontSize: ScreenUtil().setSp(11),
                                                              fontWeight: FontWeight.w300,
                                                              color: Color.fromRGBO(133, 133, 133, 1),
                                                              height: 1,
                                                            ),
                                                          ),
                                                        ),
                                                        Offstage(
                                                          offstage: !_remarkList[index].containsKey("teacherContentVoice")||_remarkList[index]["teacherContentVoice"]=="",
                                                          child: GestureDetector(
                                                            child: Image.asset("assets/images/mine/ydp_bfanky.png"),
                                                            onTap: (){
                                                              audioPlayer.stop();
                                                              audioPlayer.play(_remarkList[index]["teacherContentVoice"]);
                                                            },
                                                          )
                                                        )
                                                      ],
                                                    ),
                                                  )
                                                ],
                                              ),
                                              Container(
                                                height: 41,
                                                width: 41,
                                                margin: EdgeInsets.only(left: 10),
                                                child: CircleAvatar(
                                                  backgroundImage: NetworkImage(_remarkList[index]['teacherAvatar'] != null ? _remarkList[index]['teacherAvatar'] : ''),
                                                  radius: ScreenUtil().setWidth(20.5),
                                                ),
                                              ),
                                            ],
                                          ),
                                          Container(
                                            margin: EdgeInsets.only(right: 51,top: 10,left: 51),
                                            alignment: Alignment.topRight,
                                            child: Column(
                                              crossAxisAlignment: CrossAxisAlignment.start,
                                              children: <Widget>[
                                                Column(
                                                  crossAxisAlignment: CrossAxisAlignment.end,
                                                  children: <Widget>[
                                                    Text(_remarkList[index]['teacherContent']!=null  ? _remarkList[index]['teacherContent'] :"暂无评价",),
                                                    Container(
                                                        height: 0,
                                                        child: Text( _courseDetail['taskTitle'],style: TextStyle(fontSize: ScreenUtil().setSp(11),),)
                                                    ),

                                                  ],
                                                ),
                                                Container(
                                                  decoration: BoxDecoration(
                                                      border: Border.all(
                                                        color: Color.fromRGBO(133, 133, 133, 1),
                                                        width: ScreenUtil().setHeight(0.5),
                                                      ),
                                                      borderRadius: BorderRadius.circular(2)
                                                  ),
                                                  margin: EdgeInsets.only(top: 10),
                                                  padding: EdgeInsets.all(3),
                                                  child: Text(
                                                    _courseDetail['taskTitle'],
                                                    maxLines: 1,
                                                    overflow: TextOverflow.ellipsis,
                                                    style: TextStyle(
                                                      fontFamily: 'PingFangSC-Regular',
                                                      fontSize: ScreenUtil().setSp(11),
                                                      color: Color.fromRGBO(133, 133, 133, 1),
                                                    ),
                                                  ),
                                                ),
                                              ],
                                            ),
                                          ),
                                        ],
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            );
                          },
                        ),
                      ),
                    ),
                  ],
                ),
              ),
              Positioned(
                top: 0,
                child: Container(
                  width: MediaQuery.of(context).size.width,
                  decoration: BoxDecoration(
                    color: Colors.white,
                    border: Border(
                      bottom: BorderSide(
                        color: Color.fromRGBO(248, 248, 248, 1),
                        width: ScreenUtil().setHeight(7.5),
                      ),
                    ),
                  ),
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Container(
                        width: ScreenUtil().setWidth(50),
                        height: ScreenUtil().setHeight(44),
                        child: IconButton(
                          icon: Icon(
                            Icons.chevron_left,
                            size: ScreenUtil().setSp(30),
                          ),
                          onPressed: () {
                            Navigator.pop(context);
                            widget.update(_courseDetail['taskId'],_courseDetail['boolShareEnum'],_courseDetail['boolPunchClockEnum']);
                          },
                        ),
                      ),
                      GestureDetector(
                        child: Container(
                          width: (MediaQuery.of(context).size.width) / 2 -
                              ScreenUtil().setWidth(50),
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: <Widget>[
                              Container(
                                height: ScreenUtil().setHeight(42.5),
                                padding: EdgeInsets.only(
                                  top: ScreenUtil().setHeight(16),
                                ),
                                child: Text(
                                  '课程详情',
                                  style: TextStyle(
                                    fontFamily: 'PingFangSC-Medium',
                                    fontSize: ScreenUtil().setSp(16),
                                    fontWeight: FontWeight.w600,
                                    color: _currentTab == 0
                                        ? Color.fromRGBO(210, 180, 142, 1)
                                        : Color.fromRGBO(51, 51, 51, 1),
                                    height: 1,
                                  ),
                                ),
                              ),
                              Offstage(
                                offstage: _currentTab != 0,
                                child: Container(
                                  width: ScreenUtil().setWidth(20),
                                  height: ScreenUtil().setHeight(1.5),
                                  color: Color.fromRGBO(210, 180, 142, 1),
                                ),
                              )
                            ],
                          ),
                        ),
                        onTap: () {
                          setState(() {
                            _currentTab = 0;
                          });
                        },
                      ),
                      GestureDetector(
                        child: Container(
                          width: (MediaQuery.of(context).size.width) / 2 -
                              ScreenUtil().setWidth(50),
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: <Widget>[
                              Container(
                                height: ScreenUtil().setHeight(42.5),
                                padding: EdgeInsets.only(
                                  top: ScreenUtil().setHeight(16),
                                ),
                                child: Text(
                                  '功课点评',
                                  style: TextStyle(
                                    fontFamily: 'PingFangSC-Medium',
                                    fontSize: ScreenUtil().setSp(16),
                                    fontWeight: FontWeight.w600,
                                    color: _currentTab == 1
                                        ? Color.fromRGBO(210, 180, 142, 1)
                                        : Color.fromRGBO(51, 51, 51, 1),
                                    height: 1,
                                  ),
                                ),
                              ),
                              Offstage(
                                offstage: _currentTab != 1,
                                child: Container(
                                  width: ScreenUtil().setWidth(20),
                                  height: ScreenUtil().setHeight(1.5),
                                  color: Color.fromRGBO(210, 180, 142, 1),
                                ),
                              ),
                            ],
                          ),
                        ),
                        onTap: () {
                          setState(() {
                            _page =1;
                            _currentTab = 1;
                            if(_videoPlayerController!=null){
                              _videoPlayerController.pause();
                            }
                          });
                          _getMark(_courseDetail['taskId']);
                        },
                      ),
                    ],
                  ),
                ),
              ),
              Positioned(
                bottom: 0,
                child: Container(
                  width: MediaQuery.of(context).size.width,
                  padding: EdgeInsets.only(
                    top: ScreenUtil().setHeight(6.5),
                    bottom: ScreenUtil().setHeight(6.5),
                  ),
                  decoration: BoxDecoration(
                    color: Colors.white,
                    border: Border(
                      top: BorderSide(
                        color: Color.fromRGBO(248, 248, 248, 1),
                        width: ScreenUtil().setHeight(7.5),
                      ),
                    ),
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: <Widget>[
                      GestureDetector(
                        child: Row(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: <Widget>[
                            Icon(Icons.navigate_before,
                              color: Color.fromRGBO(186, 188, 193, 1),
                            ),
                            Text(
                              '上一个',
                              style: TextStyle(
                                fontFamily: 'PingFangSC-Regular',
                                fontSize: ScreenUtil().setSp(14),
                                color:_courseDetail['hasPreviousPage'] ?  Color.fromRGBO(51, 51, 51, 1) :Colors.grey,
                                height: 1,
                              ),
                            ),
                          ],
                        ),
                        onTap: () {
                          if(!_courseDetail['hasPreviousPage']){
                            return;
                          }else{
                            setState(() {
                              _page =1;
                              isLoading = false;
                            });
                            Request().post<Map<String,dynamic>>("/multiapi/c191v_task",data: {"id": _courseDetail['previousPageId'],"courseSectionId":_courseDetail['courseSectionId']}).then((response){
                              setState(() {
                                _courseDetail=response.data;
                                _courseId = _courseDetail['courseId'];
                                _getMark(_courseDetail['taskId']);
                                if(_videoPlayerController!=null){
                                  _videoPlayerController.pause();
                                }
                                initVideo(_courseDetail['taTaskContentList']);
                              });
                            });
                          }
                          print('上一个');
                        },
                      ),
                      Offstage(
                        offstage: Global.profile.userTypeEnum == 2,
                        child: Container(
                          width: ScreenUtil().setWidth(100),
                          height: ScreenUtil().setHeight(35),
                          decoration: BoxDecoration(
                            color: _courseDetail['boolPunchClockEnum']==1 ? Color.fromRGBO(246, 246, 246, 1) : Color.fromRGBO(214, 178, 128, 1),
                            borderRadius: BorderRadius.all(
                              Radius.circular(ScreenUtil().setHeight(4)),
                            ),
                          ),
                          child: FlatButton(
                            padding: EdgeInsets.all(0),
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.all(
                                Radius.circular(ScreenUtil().setHeight(4)),
                              ),
                            ),
                            child: Text(
                              _courseDetail['boolPunchClockEnum']==1 ? '已打卡' : '打卡',
                              style: TextStyle(
                                fontFamily: 'PingFangSC-Regular',
                                fontSize: ScreenUtil().setSp(15),
                                color: _courseDetail['boolPunchClockEnum']==1 ? Color.fromRGBO(153, 153, 153, 1) : Colors.white,
                              ),
                            ),
                            onPressed:_courseDetail['boolPunchClockEnum']==1 ? null :()=>_dk(),
                          ),
                        ),
                      ),
                      Offstage(
                        offstage: Global.profile.userTypeEnum == 2,
                        child: Container(
                          width: ScreenUtil().setWidth(100),
                          height: ScreenUtil().setHeight(35),
                          decoration: BoxDecoration(
                            color: _courseDetail['boolShareEnum']==1 ? Color.fromRGBO(246, 246, 246, 1) : Color.fromRGBO(214, 178, 128, 1),
                            borderRadius: BorderRadius.all(
                              Radius.circular(ScreenUtil().setHeight(4)),
                            ),
                          ),
                          child: FlatButton(
                            padding: EdgeInsets.all(0),
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.all(
                                Radius.circular(ScreenUtil().setHeight(4)),
                              ),
                            ),
                            child: Text(
                              _courseDetail['boolShareEnum']==1 ? '已分享' : '分享',
                              style: TextStyle(
                                fontFamily: 'PingFangSC-Regular',
                                fontSize: ScreenUtil().setSp(15),
                                color: _courseDetail['boolShareEnum']==1 ? Color.fromRGBO(153, 153, 153, 1) : Colors.white,
                              ),
                            ),
                            onPressed: _courseDetail['boolShareEnum']==1  ? null : ()=>_fx(),
                          ),
                        ),
                      ),
                      GestureDetector(
                        child: Row(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: <Widget>[
                            Text(
                              '下一个',
                              style: TextStyle(
                                fontFamily: 'PingFangSC-Regular',
                                fontSize: ScreenUtil().setSp(14),
                                color: _courseDetail['hasNextPage'] ? Color.fromRGBO(51, 51, 51, 1): Colors.grey,
                                height: 1,
                              ),
                            ),
                            Icon(Icons.navigate_next,
                              color: Color.fromRGBO(186, 188, 193, 1),
                            ),
                          ],
                        ),
                        onTap: () {
                          if(!_courseDetail['hasNextPage']){
                           return;
                          }else{
                            setState(() {
                              _page =1;
                              isLoading = false;
                            });
                            Request().post<Map<String,dynamic>>("/multiapi/c191v_task",data: {"id": _courseDetail['nextPageId'],"courseSectionId":_courseDetail['courseSectionId']}).then((response){
                              setState(() {
                                _courseDetail=response.data;
                                _courseId = _courseDetail['courseId'];
                                _getMark(_courseDetail['taskId']);
                                if(_videoPlayerController!=null){
                                  _videoPlayerController.pause();
                                }
                                initVideo(_courseDetail['taTaskContentList']);
                              });
                            });
                          }
                          print('下一个');
                        },
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
  _dk(){
    Request().post("/multiapi/c195c_studyRecord",
        data: {
          "taskId": _courseDetail['taskId'],
          "courseId": _courseId
        }).then((response){
          if(response.code == 200){
            setState(() {
              _courseDetail['boolPunchClockEnum']=1;
            });
            Request().toast("打卡成功");
          }else{
            Request().toast(response.msg);
          }
    });

    print('打卡');
  }
  _fx(){
    print('分享');
    Navigator.push(context, MaterialPageRoute(builder: (context) => Share(_courseDetail,_courseId,()=>_update())));
  }

  //获取点评
  _getMark(taskId) {
    if(isLoading){
      return;
    }
    setState(() {
      isLoading = true;
    });
    Request().post<Map<String,dynamic>>("/multiapi/c192p_studyRecord",
        data:{
          "courseId": _courseId,
          "taskId": taskId,
          "pageNum": _page,
          "pageSize": 10
        }).then((response){
      setState(() {
        _remarkList = response.data['list'];
        _remarkList.forEach((element) {
          element['isPlayAudio'] = false;
          element['initSchedule'] = 0;
          element['currentSchedule'] = 0.0;

          element['teacherIsPlayAudio'] = false;
          element['teacherInitSchedule'] = 0;
          element['teacherCurrentSchedule'] = 0.0;

        });
        _page += 1;
        if(!response.data["isLastPage"]){
          isLoading =false;
        }
      });
    });
  }

  Future<Null> _refresh() async {
    setState(() {
      _page =1;
      isLoading = false;
    });
    if(_currentTab ==1){
      _getMark(_courseDetail['taskId']);
    }

    return null;
  }

  _update() {
    Request().post<Map<String,dynamic>>("/multiapi/c191v_task",data: {"id": _courseDetail['taskId'],"courseSectionId":_courseDetail['courseSectionId']}).then((response){

      // 初始化视频
      initVideo(response.data['taTaskContentList']);
      setState(() {
        _courseDetail=response.data;
      });
    });
    _refresh();
  }
  //视频播放
  _videoPlay(index,_cache) async {


    bool net = await UtilFun.checkNetwork(context);
    if(!net) return;
    if(_videoPlayerController!=null){
      _videoPlayerController.pause();
    }
    //切换视频
    if(currVideo != index){
      setState(() {
        _videoPlayerController =
        VideoPlayerController.network(_cache[index]['taskContentContent'])..addListener(() async {
          if(_videoPlayerController.value.isPlaying){
            if(audioPlayer.state == AudioPlayerState.PLAYING){
              audioPlayer.pause();
            }
            bool isKeptOn = await Screen.isKeptOn;
            if(!isKeptOn){
              print("常亮");
              Screen.keepOn(true);
            }
          }
        });
        setState(() {
          _courseDetail['taTaskContentList'].forEach((element) {
            if(element['isPlayAudio'] == true){
              element['isPlayAudio'] =false;
            }
          });
          if(_timer!=null){
            _timer.cancel();
            _timer = null;
          }
        });
        _chewieController = ChewieController(
          aspectRatio: 2/1,
          videoPlayerController: _videoPlayerController,
          autoInitialize: true,
          deviceOrientationsAfterFullScreen: [
            DeviceOrientation.portraitUp,
            DeviceOrientation.portraitDown
          ],
        );

        _cache.forEach((element) {
          element['videoPaly'] =false;
        });
      });
      setState(() {
        _cache[index]['videoPaly'] =true;
      });
      _videoPlayerController.play();
    }else{
      bool isKeptOn = await Screen.isKeptOn;

      if(_videoPlayerController!=null){
        if(_videoPlayerController.value.isPlaying){
          _videoPlayerController.pause();
          if(!isKeptOn){
            print("关常亮");
            Screen.keepOn(false);
          }
        }else{
          if(isKeptOn){
            print("常亮");
            Screen.keepOn(true);
          }
          _videoPlayerController.play();
        }
      }
    }
  }


}
